using AutoMapper;
using MediatR;
using Medical.Api.Write.Application.Command.BasicManagement.DeviceDictionaryCommand;
using Medical.Domain.BasicManagement;
using Medical.ErrorCode;
using Medical.Interstructrue.Base;

namespace Medical.Api.Write.Application.Handler.BasicManagement.DeviceDictionaryHandler
{
    /// <summary>
    /// 创建设备命令处理器
    /// </summary>
    public class CreateEquipmentHandler : IRequestHandler<CreateEquipmentCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Equipment> _equipmentRepository;
        private readonly IMapper _mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="equipmentRepository">设备仓储</param>
        /// <param name="mapper">AutoMapper</param>
        public CreateEquipmentHandler(IBaseRepository<Equipment> equipmentRepository, IMapper mapper)
        {
            _equipmentRepository = equipmentRepository;
            _mapper = mapper;
        }

        /// <summary>
        /// 处理创建设备命令
        /// </summary>
        /// <param name="request">命令请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>操作结果</returns>
        public Task<ApiResult<int>> Handle(CreateEquipmentCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var equipment = _mapper.Map<Equipment>(request.EquipmentData);

                var result = _equipmentRepository.Create(equipment);

                if (result <= 0)
                {
                    return Task.FromResult(new ApiResult<int>
                    {
                        Code = ApiEnums.Fail,
                        Msg = "设备添加失败",
                        Data = 0
                    });
                }

                return Task.FromResult(new ApiResult<int>
                {
                    Code = ApiEnums.Success,
                    Msg = "设备添加成功",
                    Data = equipment.Id
                });
            }
            catch (AutoMapperMappingException ex)
            {
                return Task.FromResult(new ApiResult<int>
                {
                    Code = ApiEnums.Error,
                    Msg = $"设备数据映射失败: {ex.Message}",
                    Data = 0
                });
            }
        }
    }
}